package com.tenement.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tenement.common.GlobalException;
import com.tenement.common.RedisConConstant;
import com.tenement.config.SecurityConfig;
import com.tenement.dto.LoginUserDto;
import com.tenement.enums.RespBusiness;
import com.tenement.utils.JwtUtil;
import com.tenement.utils.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (Arrays.asList(SecurityConfig.AUTH_WHITELIST).contains(request.getServletPath())) {
            filterChain.doFilter(request, response);
            return;
        }
        String authHeader = request.getHeader(JwtUtil.TOKEN_AUTHORIZATION);
        if(StrUtil.isEmpty(authHeader)) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            Claims claims = JwtUtil.parseJWT(authHeader);
            LoginUserDto loginUserDto = redisCache.getValue(RedisConConstant.USER_LOGIN_TOKEN + claims.getSubject(), LoginUserDto.class);
            if(ObjectUtil.isNull(loginUserDto)) {
                errorResponse(response,RespBusiness.TOKEN_ILLEGAL);
            }
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUserDto, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response);
        } catch (ExpiredJwtException e) {
            redisCache.delete(RedisConConstant.USER_LOGIN_TOKEN + e.getClaims().getSubject());
            errorResponse(response,RespBusiness.TOKEN_ILLEGAL);
        }
        catch (Exception e) {
            errorResponse(response,RespBusiness.FAIL);
        }
    }


    private static void errorResponse(HttpServletResponse response, RespBusiness respBusiness) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = response.getWriter();
        JSONObject res = new JSONObject();
        res.put("code", respBusiness.getCode());
        res.put("msg",respBusiness.getMsg());
        res.put("data",null);
        writer.write(JSON.toJSONString(res));
        writer.flush();
        writer.close();
    }
}
